<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="addList">添加角色</el-button>
      <el-table :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row class="top" v-for="item in scope.row.children" :key="item.id">
              <el-col :span="5">
                <el-tag closable @close="delRolues(scope.row, item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="item2 in item.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="delRolues(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id"
                      @close="delRolues(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="level">
          <template slot-scope="scope">
            <el-button type="primary" size="small" class="el-icon-edit" @click="modForm(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" class="el-icon-delete" @click="delForm(scope.row.id)">删除</el-button>
            <el-button type="info" size="small" class="el-icon-setting" @click="handleClose(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addCateDialogVisible">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="addCateForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="addCateForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="dialogVisible" @close="setRightDialogClose">
      <el-tree :data="rightsList" :default-checked-keys="defKeys" show-checkbox node-key="id" default-expand-all
        :props="treeProps" ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog title="修改角色" :visible.sync="editCateDialogVisible">
      <el-form :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef" label-width="100px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="editCateForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="editCateForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      rolesList: [],
      dialogVisible: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: '',
      addCateForm: {
        roleName: '',
        roleDesc: ''
      },
      addCateFormRules: {
        roleName: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        roleDesc: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }]
      },
      addCateDialogVisible: false,
      editCateDialogVisible: false,
      editCateForm: [],
      editCateFormRules: {
        roleName: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        roleDesc: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    async getRolesList () {
      const {
        data: res
      } = await this.$http.get('http://kb.dekunlu.top/api/private/v1/roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rolesList = res.data
    },
    async delRolues (item, id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const {
        data: res
      } = await this.$http.delete(`http://kb.dekunlu.top/api/private/v1/roles/${item.id}/rights/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      item.children = res.data
    },
    async modForm (id) {
      const {
        data: res
      } = await this.$http.get(`http://kb.dekunlu.top/api/private/v1/roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取信息失败')
      }
      this.editCateForm = res.data
      this.editCateDialogVisible = !this.editCateDialogVisible
    },
    editRoleInfo () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        const {
          data: res
        } = await this.$http.put(
          'http://kb.dekunlu.top/api/private/v1/roles/' + this.editCateForm.roleId,
          this.editCateForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败！')
        }
        this.$message.success('修改角色信息成功！')
        this.editCateDialogVisible = false
        this.getRolesList()
      })
    },
    // 添加
    addList () {
      this.addCateDialogVisible = true
    },
    addRoleInfo () {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整用户信息')
        const {
          data: res
        } = await this.$http.post('http://kb.dekunlu.top/api/private/v1//roles', this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.getRolesList()
      })
      this.addCateDialogVisible = false
    },
    async delForm (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const {
        data: res
      } = await this.$http.delete('http://kb.dekunlu.top/api/private/v1/roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getRolesList()
    },
    async handleClose (role) {
      this.roleId = role.id
      const {
        data: res
      } = await this.$http.get('http://kb.dekunlu.top/api/private/v1/rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightsList = res.data
      this.getLeafKeys(role, this.defKeys)
      this.dialogVisible = true
    },
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClose () {
      this.defKeys = []
    },
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {
        data: res
      } = await this.$http.post(`http://kb.dekunlu.top/api/private/v1/roles/${this.roleId}/rights`, {
        rids: idStr
      })
      console.log(this.roleId)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
  ::before {
    margin-right: 5px;
  }

  .el-tag {
    margin: 7px
  }

  .bdtop {
    border-top: 1px solid #eee
  }

  .bdbottom {
    border-bottom: 1px solid #eee
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
